// pages/chat/chat.ts
import { caseIdentify } from '../../api/ai';
import { addVideo, getMyVideoList } from '../../api/video';
import { debounce } from '../../utils/debounce'
import { login } from '../../utils/login';

Page({
  /**
   * 页面的初始数据
   */
  data: <any>{
    active: 1,
    showJoinWebinarDialog: false,
    editorValue: '',
    aiContent: {
      change: "",
      diagnosisTime: "",
      disease: "",
      hospital: "",
      programme: [],
      treatment: []
    },
    videoList: [],
    formInfo: {
      userId: '',
      title: '',
      hospital: '',
      name: '',
      guide: '',
      detail: '',
      videoUrl: '',
      fileList: []
    },
  },

  handleInput(e: any){
    const value = e.detail.value;
    const { flag } = e.currentTarget.dataset
    const f: any = {}
    f[flag] = value;

    this.setData({
      formInfo: {
        ...this.data.formInfo,
        ...f
      }
    })
  },

  async getList(){
    const res = await getMyVideoList({
      pageSize: 999,
      pageNum: 1
    })

    if(res && res.rows){
      this.setData({
        videoList: res.rows
      })
    }
  },

  openDetail(e: any){
    wx.navigateTo({
      url: '/pages/guideDetail/guideDetail',
      success: (res) => {
        res.eventChannel.emit('acceptDataFromOpenerPage', e.currentTarget.dataset.item)
      }
    });
  },

  caseHandle(data: any){
    const { index } = data.currentTarget.dataset
    this.setData({
      active: index
    })

    if(index === '2'){
      this.getList()
    }
  },

  backToCase(){
    wx.navigateBack({
      delta: 1 
    });
  },

  ensure(json: any){
    getApp().globalData.caseUploadFileContent = json
    wx.navigateTo({
      url: '/pages/ensureCase/ensureCase'
    });
  },

  chosePicture(){
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      camera: 'back',
      success: (res) => {
        const tempFiles = res.tempFiles;
        const file = tempFiles[0];
        const { tempFilePath } = file;
        if(tempFilePath){
          this.uploadFile(tempFilePath).then((res: any) => {
            if(res?.url){
              this.setData({
                formInfo: {
                  ...this.data.formInfo,
                  thumb: res.url
                }
              })
            }
          })
        }
      }
    })
  },

  choseFile(){
    wx.chooseMessageFile({
      count: 1,
      type: 'file',
      success: (res) => {
        wx.showLoading({
          title: '加载中',
        })
        const tempFiles = res.tempFiles;
        const file = tempFiles[0];
        const { path } = file;
        if(path){
          this.uploadFile(path).then((res: any) => {
            caseIdentify({
              type: '2',
              fileName: res.fileName
            }).then((res: any) => {
              wx.hideLoading()
              const { choices } = res;
              if(choices && choices[0]){
                const message = choices[0]?.message?.content;
                if(message){
                  let json = this.formatAiMessage(message);
                  this.ensure(json)
                }
              }else{
                wx.showToast({
                  title: '识别不正确',
                  icon: 'error',
                  duration: 2000,
                })
                console.log(res)
              }
            }).catch(e => {
              wx.hideLoading()
              wx.showToast({
                title: '识别出错了',
                icon: 'error',
                duration: 2000,
              })
              console.log(e)
            })
          })
        }
      }
    });
  },

  editorInputHandle: debounce((e: any, context: any) => {
    const { text } = e.detail;
    context.setData({
      editorValue: text
    })
  }),

  uploadVideo(){
    const userInfo = login()
    const formInfo = {
      ...this.data.formInfo,
      userId: userInfo.id
    }

    if(
      !formInfo ||
      !formInfo.title || 
      !formInfo.hospital || 
      !formInfo.name ||
      !formInfo.guide ||
      !formInfo.detail || 
      !formInfo.videoUrl ||
      !formInfo.thumb
    ){
      wx.showToast({
        title: '请填写表单',
        icon: 'error',
        duration: 2000,
      })
    }

    if(userInfo){
      addVideo(formInfo).then(res => {
        console.log(res)
        this.backToCase()
      }).catch(e  => {
        wx.showToast({
          title: '上传失败',
          icon: 'error',
          duration: 2000,
        })
      })
      // wx.hideLoading()
    }

    
  },

  formatAiMessage(message: string){
    const jsonRegex = /```json\s*(\{[\s\S]*\})\s*```/;
    const match = message.match(jsonRegex);

    if (match && match[1]) {
      try {
        const jsonObject = JSON.parse(match[1]);
        return jsonObject;
      } catch (e) {
        console.error('Failed to parse JSON:', e);
        return null;
      }
    } else {
      console.error('No JSON object found in the string.');
      return null;
    }
  },

  uploadFile(filePath: string){
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: 'https://caca.zn-care.com/api/common/upload', // 开发者服务器接口地址
        filePath,
        name: 'file',
        header: {
          Authorization:  `Bearer ${wx.getStorageSync('token')}`
        },
        success: uploadResult => {
          const data = uploadResult.data
          const jsonRes = JSON.parse(data)
          const { url, fileName } = jsonRes
          if(url){
            resolve({
              url, 
              fileName
            })
          }
        },
        fail: uploadError => {
          wx.hideLoading()
          wx.showToast({
            title: '上传出错',
            icon: 'error',
            duration: 2000,
          })
          reject(uploadError);
        }
      });
    })
  },
  editorCtx: <any>null,
  onEditorReady() {
    const that = this
    wx.createSelectorQuery().select('#editor').context(function (res) {
      that.editorCtx = res.context
    }).exec()
  },

  format(e: any) {
    let { name, value } = e.target.dataset
    if (!name) return
    this.editorCtx.format(name, value)
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    getApp().globalData.caseUploadFileContent = {}
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    try {
      this.data.requestTask.abort()
    } catch (error) {
      console.log('还没发请求就退出了，正常不会有影响')
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      "title": "",
      "path": `pages/home/home?active=1`,
      "imageUrl": "/static/img/home.jpg"
    }
  }
})